"""Функции для работы c бд Firebird."""
import logging
from collections import defaultdict

import firebirdsql

import config


def select(sql):  # noqa: ANN201
    """Выборка из бд firebird.

    Args:
    ----
        sql (str): sql запрос на выборку

    Returns:
    -------
        tuple: tuple c list внутри
    """
    con = firebirdsql.connect(dsn=config.dsn, user=config.user, password=config.password, charset=config.charset)
    cur = con.cursor()
    cur.execute(sql)
    result = cur.fetchall()
    cur.close()
    del cur
    return result


def write(sql) -> None:
    """Запись данных в бд firebird.

    Args:
    ----
        sql (str): sql запрос для записи данных в бд
    """
    try:
        con = firebirdsql.connect(dsn=config.dsn, user=config.user, password=config.password, charset=config.charset)
        cur = con.cursor()
        cur.execute(sql)
        con.commit()
        cur.close()
        del cur
    except Exception:
        logging.exception("Found an error")


def proc(proc_name):  # noqa: ANN201
    """Выполнение процедуры fb.

    Args:
    ----
        proc_name (_type_): _description_

    Returns:
    -------
        tuple: возвращает результат выполнения процедуры
    """
    con = firebirdsql.connect(dsn=config.dsn, user=config.user, password=config.password, charset=config.charset)
    cur = con.cursor()
    cur.callproc(proc_name)
    output_params = cur.fetchone()
    con.commit()
    return output_params


def select_dicts_in_turple(sql):  # noqa: ANN201
    """_summary_.

    Args:
    ----
        sql (_type_): _description_

    Returns:
    -------
        _type_: _description_
    """
    con = firebirdsql.connect(dsn=config.dsn, user=config.user, password=config.password, charset=config.charset)
    cur = con.cursor()
    cur.execute(sql)
    result = {}
    fieldIndices = range(len(cur.description))  # noqa: N806
    selectFields = ()  # noqa: N806
    for fieldDesc in cur.description:  # noqa: N806
        selectFields = *selectFields, fieldDesc[firebirdsql.DESCRIPTION_NAME]  # noqa: N806
    m = ""
    id = 0  # noqa: A001
    result = defaultdict(list)
    for row in cur:
        color_ = "table-light"
        for fieldIndex in fieldIndices:  # noqa: N806
            if "ID_GRF" in selectFields[fieldIndex]:
                id = row[fieldIndex]  # noqa: A001
            if "YEARWORK" in selectFields[fieldIndex]:
                row[fieldIndex]
            if "MONTHWORK" in selectFields[fieldIndex]:
                m = str(row[fieldIndex])
                if len(m) == 1:
                    m = f"0{m}"
            if "DAY" in selectFields[fieldIndex]:
                (selectFields[fieldIndex])[3:5]
                if row[fieldIndex] == "НП":
                    color_ = "table-warning"
            key = f"{id}"
            result[key].append(color_)
            result[key].append(row[fieldIndex])

    cur.close()
    del cur
    return result


def select_dicts_in_turple2(sql):  # noqa: ANN201
    """Выборка данных из бд fb словарями и объединение в tuple.

    Args:
    ----
        sql (str): sql запрос на выборку

    Returns:
    -------
        tuple: dicts in tuple
    """
    con = firebirdsql.connect(dsn=config.dsn, user=config.user, password=config.password, charset=config.charset)
    cur = con.cursor()
    cur.execute(sql)
    result = {}
    fieldIndices = range(len(cur.description))  # noqa: N806
    selectFields = ()  # noqa: N806
    for fieldDesc in cur.description:  # noqa: N806
        selectFields = *selectFields, fieldDesc[firebirdsql.DESCRIPTION_NAME]  # noqa: N806
    result2 = ()
    for row in cur:
        for fieldIndex in fieldIndices:  # noqa: N806
            result[selectFields[fieldIndex]] = row[fieldIndex]
        result2 = (*result2, result)
    cur.close()
    del cur
    return result2


def sel_dict_in_turple_desc(sql) -> list:
    """Формирование кортежа из словарей
        вида ключ:значение, где ключ берется из название столбца в запросе
    Args:
        sql (str): sql для выборки
    Returns:
        tuple: dicts in tuple.
    """  # noqa: D205
    con = firebirdsql.connect(dsn=config.dsn, user=config.user, password=config.password, charset=config.charset)
    cur = con.cursor()
    cur.execute(sql)
    select_fields = ()
    for field_desc in cur.description:
        select_fields = *select_fields, field_desc[firebirdsql.DESCRIPTION_NAME]
    dict_select = {}
    result_4 = []
    for row in cur:
        for i, _ in enumerate(select_fields):
            dict_select[select_fields[i]] = row[i]
        result_4.append(dict_select)
        dict_select = {}
    cur.close()
    del cur
    return result_4


def sel_dict_in_list_desc(sql) ->list:
    """Формирование списка из словарей
        вида ключ:значение, где ключ берется из название столбца в запросе
    Args:
        sql (str): sql для выборки
    Returns:
        list: dicts in list.
    """  # noqa: D205
    con = firebirdsql.connect(dsn=config.dsn, user=config.user, password=config.password, charset=config.charset)
    cur = con.cursor()
    cur.execute(sql)
    select_fields = ()
    for field_desc in cur.description:
        select_fields = *select_fields, field_desc[firebirdsql.DESCRIPTION_NAME]
    dict_select = {}
    result = []
    for row in cur:
        for i, _ in enumerate(select_fields):
            dict_select[select_fields[i]] = row[i]
        result.append(dict_select)
        dict_select = {}
    cur.close()
    del cur
    return result


def sel_dict_in_list_lowerkeys(sql) -> list:
    """Формирование списка из словарей
        вида ключ:значение, где ключ берется из название столбца в запросе
    Args:
        sql (str): sql для выборки
    Returns:
        list: dicts in list.
    """  # noqa: D205
    con = firebirdsql.connect(dsn=config.dsn, user=config.user, password=config.password, charset=config.charset)
    cur = con.cursor()
    cur.execute(sql)
    select_fields = ()
    for field_desc in cur.description:
        select_fields = *select_fields, (field_desc[firebirdsql.DESCRIPTION_NAME]).lower()
    dict_select = {}
    result = []
    for row in cur:
        for i, _ in enumerate(select_fields):
            dict_select[select_fields[i]] = row[i]
        result.append(dict_select)
        dict_select = {}
    cur.close()
    del cur
    return result


def sel_dict_in_list_desc1(sql) -> dict:
    """Формирование списка из словарей
        вида ключ:значение, где ключ берется из название столбца в запросе
    Args:
        sql (str): sql для выборки
    Returns:
        list: dicts in list.
    """  # noqa: D205
    con = firebirdsql.connect(dsn=config.dsn, user=config.user, password=config.password, charset=config.charset)
    cur = con.cursor()
    cur.execute(sql)
    result = {}
    result[0] = ""
    for row in cur:
        result[row[0]] = row[1]
    cur.close()
    del cur
    return result
